﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Urs.Core.ComponentModel
{
    public class GenericDictionaryTypeConverter : TypeConverter
    {
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            if (sourceType == typeof(string))
            {
                return true;
            }

            return base.CanConvertFrom(context, sourceType);
        }

        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                Dictionary<string, string> dicKeyValue = null;
                string valueStr = value as string;
                if (!String.IsNullOrEmpty(valueStr))
                {
                    try
                    {
                        dicKeyValue = JsonConvert.DeserializeObject<Dictionary<string, string>>(valueStr);
                    }
                    catch
                    {
                        //xml error
                    }
                }
                return dicKeyValue;
            }
            return base.ConvertFrom(context, culture, value);
        }

        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == typeof(string))
            {
                var dictKeyValue = value as Dictionary<string, string>;
                var serialized = JsonConvert.SerializeObject(dictKeyValue);
                return serialized;
            }

            return base.ConvertTo(context, culture, value, destinationType);
        }
    }
}
